package com.czmh.etc.onlinepubsys.services.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.czmh.etc.onlinepubsys.dto.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czmh.etc.common.core.utils.Sequence;
import com.czmh.etc.onlinepubsys.json.JsonResult;
import com.czmh.etc.onlinepubsys.maper.EtcApplyOrderMapper;
import com.czmh.etc.onlinepubsys.maper.EtcObuMapper;
import com.czmh.etc.onlinepubsys.maper.EtcUserMapper;
import com.czmh.etc.onlinepubsys.model.EtcApplyOrder;
import com.czmh.etc.onlinepubsys.model.EtcUser;
import com.czmh.etc.onlinepubsys.services.IEtcApplyOrderService;
import com.czmh.etc.onlinepubsys.utils.JsonResultUtil;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Seven
 * @since 2020-04-12
 */
@Service
public class EtcApplyOrderServiceImpl extends ServiceImpl<EtcApplyOrderMapper, EtcApplyOrder> implements IEtcApplyOrderService {

	@Autowired
	private EtcUserMapper etcUserMapper;
	@Autowired
	private EtcObuMapper etcObuMapper;
	
	@Override
	public JsonResult saveOrderInfo(EtcApplyOrder order) {
		EtcUser e = etcUserMapper.getById(order.getId());
		if(e != null && e.getUser_phone() == null && e.getUser_loginname() == null){
			e.setUser_loginname(order.getPhoneNum());
			e.setUser_phone(order.getPhoneNum());
			etcUserMapper.update(e);
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("user_phone", order.getPhoneNum());
		List<EtcUser> list = etcUserMapper.getAll(params);
		if (list.isEmpty()) {
			EtcUser etcUser = new EtcUser(Sequence.getId());
			etcUser.setUser_loginname(order.getPhoneNum());
			etcUser.setUser_name(order.getName());
			etcUser.setUser_phone(order.getPhoneNum());
			etcUser.setUser_sex(order.getSex());
			etcUser.setCreate_time(new Date());
			etcUser.setUpdate_time(new Date());
			etcUserMapper.insert(etcUser);
		}
		list = etcUserMapper.getAll(params);
		EtcUser etcUser = list.get(0);
		order.setUserId(etcUser.getUser_id());
        QueryWrapper<EtcApplyOrder> queryWrapper = new QueryWrapper<EtcApplyOrder>();
        queryWrapper.lambda().eq(EtcApplyOrder::getOrderId, order.getOrderId());
		EtcApplyOrder applyOrder = this.getOne(queryWrapper);
		if (applyOrder != null) {
			order.setId(applyOrder.getId());
		}
		this.saveOrUpdate(order);
		params.clear();
		params.put("obuNum", order.getObuNum());
		params.put("obuStatus", order.getObuStatus());
		etcObuMapper.updateObuActiveStatus(params);
		return JsonResultUtil.toResult();
	}
}
